package com.qsd.doc4jsimpple.util;

/**
 * * @Author xujunxia
 * * @Date 2024-12-05 15:46
 * * @Description TODO
 * * wb-0455@dtdream.com
 **/
import java.util.ArrayList;
import java.util.List;

public class ColorUtil {
    public static int[] hexToRgb(String hex) {
        int r = Integer.parseInt(hex.substring(1, 3), 16);
        int g = Integer.parseInt(hex.substring(3, 5), 16);
        int b = Integer.parseInt(hex.substring(5), 16);
        return new int[]{r, g, b};
    }
    public static String findNearestColor(String hex, List<String> colorSet) {
        int[] targetRgb = hexToRgb(hex);
        double minDistance = Double.MAX_VALUE;
        String nearestColor = null;
        for (String color : colorSet) {
            int[] candidateRgb = hexToRgb(color);
            double distance = Math.sqrt((targetRgb[0] - candidateRgb[0]) * (targetRgb[0] - candidateRgb[0]) +
                    (targetRgb[1] - candidateRgb[1]) * (targetRgb[1] - candidateRgb[1]) +
                    (targetRgb[2] - candidateRgb[2]) * (targetRgb[2] - candidateRgb[2]));
            if (distance < minDistance) {
                minDistance = distance;
                nearestColor = color;
            }
        }
        return nearestColor;
    }


    public static String getNearestColor(String hex) {
        List<String> colorSet = new ArrayList<>();
        colorSet.add("#000000");
        colorSet.add("#0000FF");
        colorSet.add("#00FFFF");
        colorSet.add("#008000");

        colorSet.add("#FF00FF");
        colorSet.add("#FF0000");
        colorSet.add("#FFFF00");
        colorSet.add("#FFFFFF");


        colorSet.add("#00008B");
        colorSet.add("#008B8B");
        colorSet.add("#006400");
        colorSet.add("#8B008B");

        colorSet.add("#8B0000");
        colorSet.add("#FFD700");
        colorSet.add("#A9A9A9");
        colorSet.add("#D3D3D3");
        return findNearestColor(hex, colorSet);
    }
    public static void main(String[] args) {
        String givenHex = "#123456";
        List<String> colorSet = new ArrayList<>();
        colorSet.add("#000000");
        colorSet.add("#0000FF");
        colorSet.add("#00FFFF");
        colorSet.add("#008000");

        colorSet.add("#FF00FF");
        colorSet.add("#FF0000");
        colorSet.add("#FFFF00");
        colorSet.add("#FFFFFF");


        colorSet.add("#00008B");
        colorSet.add("#008B8B");
        colorSet.add("#006400");
        colorSet.add("#8B008B");

        colorSet.add("#8B0000");
        colorSet.add("#FFD700");
        colorSet.add("#A9A9A9");
        colorSet.add("#D3D3D3");

        System.out.println("Nearest color to " + givenHex + " is " + findNearestColor(givenHex, colorSet));
    }
}
